Swift Structs and Classes: A Friendly Guide to Their Differences and Similarities
When your're delving into the world of Swift programming, you'll inevitably come across two essential concepts: struct
and class
. In this guide, we'll unravel the mysteries of struct and class, making them easier to understand.
Similarities
- Define properties (that including computed properties & property observer)
- Define method
- Define subscripts to provide access to their value
- Define initializers
- Be extended to expand their functionality beyond a default implementation
- These have the ability to conform to protocols and then provide functionality
Differences
class have adiitional capabilities that structure don't have.
other difference thing.
- Value Type & Reference Type
- Mutable & Immutable
- Memberwise Initializer
Syntax
this is the least code to define this struct and class, I'll show you actually example later.
struct SomeStruct {
}
class SomeClass {
}
Value Type & Reference Type
Swift struct is Value Type, this means any properties in struct instance, they always copy when they're passed around in your code.
struct Person {
var name: String
var age: Int
}
let andrew = Person(name: "Andrew", age: 22)
var eric = andrew
eric.age = 41
print(andrew.age) // print: 22
print(eric.age) // print: 41
And class is Reference Type, that aren't copied when they're passed. That reference same instance. For example, similar we defined struct above
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let andrew = Person(name: "Andrew", age: 22)
var eric = andrew
eric.age = 41
print(andrew.age) // print: 41
print(eric.age) // print: 41
Initializers
In Swift, when you create a struct and define properties, struct automatically get a initializer called Memberwise Initializer. but your must manually define a iniitializer in class
// struct
struct Person {
var name: String
var age: Int
}
let leo = Person(name: "Leo", age: 32)
// class
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let leo = Person(name: "Leo", age: 32)
Mutating
you can't modify any properties insdie method in struct by default, the solution is mark it using mutating
keyword, like this:
struct Person {
var name: String
mutating func setName(name: String) {
self.name = name
}
}